<?php
/**
 * Class Page_Be_Locale_Translations created by Havriniuc Serghei
 * Date: 10.08.12
 * Time: 15:21
 */

class Page_Be_Locale_Translations extends Page {
	function __construct() {
        self::$TPL->appendCssFile('admin/translations');
        self::$TPL->appendJsFile('admin/translations');
		parent::__construct();
	}

	public function defaultAction() {
		if (perm('TRANSLATIONS_EDIT')) {
        	$this->addBreadcrumb(t(T_FORM_BUTTON, 'add'), '?action=addEdit');
		}
		self::$TPL->setBodyTemplate('list_translations');
		return array(
			'type' => 'display'
		);
	}

	public function addEditAction() {
		perm('TRANSLATIONS_EDIT', '/locale/translations');
        $module = get('module', 'str');
        $key = get('key', 'str');
        if(empty($module) && empty($key)) {
            $this->addBreadcrumb(t(T_FORM_BUTTON, 'add'), '?action=addEdit', true);
        } else {
			$this->addBreadcrumb(t(T_FORM_BUTTON, 'edit'), '?action=addEdit', true);

			$translation = Db_Locale_Translations::getHtmlTranslationByModuleAndKey($module, $key);
			self::$TPL->assign('translation', $translation);
			$key = strtolower(get('key', 'str'));
			$module = strtolower(get('module', 'str'));
			self::$TPL->assign('key', $key);
			self::$TPL->assign('module', $module);
		}
        self::$TPL->setBodyTemplate('add_edit_translation');
		return array(
			'type' => 'display'
		);
	}

	public function getModulesAction() {
		$jsonResult = Db_Locale_Translations::getAllModules();
		return array(
			'type' => 'json',
			'content' => $jsonResult
		);
	}

	public function loadTranslationsDataAction() {
        $allColumns = array('nr', 't_module', 't_key', 't_is_html', 't_content', 'lang', 'action');
		$searchColumns = array('t_module', 't_key', 't_is_html', 't_content');
        list ($searchQuery, $orderBy, $limit) = Utils::getSqlQueriesForPagination($allColumns, $searchColumns, 'Db_Locale_Translations', 'getTotalElements');
        // Paging
        $translationsArray = Db_Locale_Translations::loadAllTrans($limit, $searchQuery, $orderBy);
        $langsId = conf('LANGS_ID');
        $langs = conf('LANGS');
        self::$TPL->assign('translationsArray', $translationsArray);
        self::$TPL->assign('langsId', $langsId);
        self::$TPL->assign('langs', $langs);
        return array(
            'type' => 'encoded_json',
            'content' => self::$TPL->display('json_list_translations', true)
        );
    }

	public function saveAction() {
		perm('TRANSLATIONS_EDIT', '/locale/translations');
		$error = false;
		$module = (get('module', 'str') ? strtolower(get('module', 'str')) : strtolower(post('t_module', 'str')));
		$key = (get('key', 'str') ? strtolower(get('key', 'str')) : strtolower(post('t_key', 'str')));
        $isHtml = post('t_is_html', 'int');
        $contents = (!empty($isHtml) ? post('t_content', true) : post('t_content') );
        $isPath = post('t_is_path', 'int');
        if (!empty($module)) {

            $firstNotEmptyValue = '';
            foreach ($contents AS $content) {
                if (empty($firstNotEmptyValue) && !empty($content)) {
                    $firstNotEmptyValue = $content;
                }
            }

            $data = array();
            foreach ($contents as $langId => $content) {
				if (empty($content) && !empty($firstNotEmptyValue)) {
					$content = $firstNotEmptyValue;
				}
				Db_Locale_Untranslated::deleteUntranslated($langId, $module, $key);
				$data[] = array(
                    't_lang_id' => $langId,
                    't_module' => $module,
                    't_key' => $key,
                    't_content' => $content,
                    't_is_path' => $isPath,
                    't_is_html' => $isHtml
                );
			}
            if (!Db_Locale_Translations::insertBatch($data, true)) {
                $error = true;
            }
            $message = (!$error ? t(T_FORM_MSG, 'success') : t(T_FORM_ERROR, 'unknown_error_occurred'));
        } else {
            $error = true;
            $message = t(T_FORM_ERROR, 'required_fields');
        }
		self::$S->message($message, $error);
		return array(
			'type' => 'redirect',
			'content' => '?action=add'
		);
	}

	public function editTranslationAction() {
		perm('TRANSLATIONS_EDIT', '/locale/translations');
		$translationModule = post('translationModule', 'string');
		$translationKey = post('translationKey', 'string');
		$translationId = (int)str_replace('translation_', '', post('id'));
		$langId = post('langId', 'int');
		if ($translationId > 0 || $addingNew = (0 == $translationId && $translationModule && $translationKey && $langId)){
			if (isset($addingNew) && $addingNew) {
				$translation = Db_Locale_Translations::findByFields(array(
					't_module' => $translationModule,
					't_key' => $translationKey
				));
				if ($translation) {
					$translation->id = null;
					$translation->t_lang_id = $langId;
				}
			} else {
				$translation = new Db_Locale_Translations($translationId);
				if (!$translation->objectArray) {
					return false;
				}
			}
			$translation->t_content = post('value', 'str');

			// If the save wasn't successful we return back the old value
			if (!$translation->save(true)) {
				return array(
					'type' => 'string',
					'content' => $translation->objectArray->t_content
				);
			}
			return array(
				'type' => 'string',
				'content' => $translation->t_content
			);
		}
		return false;
	}

    public function deleteTranslationAction(){
		perm('TRANSLATIONS_EDIT', '/locale/translations');
        $module = post('t_module', 'string');
        $key = post('t_key', 'string');
		$error = false;
        if(Db_Locale_Translations::deleteByModuleKey($module, $key)){
            $message = t(T_FORM_MSG, 'delete_msg_true');
        } else {
            $error = true;
            $message = t(T_FORM_MSG, 'delete_msg_false');
        }
        return array(
            'type' => 'encoded_json',
            'content' => $this->jsonResult($error, $message, !$error)
        );
    }

    public function saveTranslationsAction() {
		perm('TRANSLATIONS_EDIT', '/locale/translations');
        $allTranslations = post('translations', 'array');
        $redirect = post('redirect', 'string');
        $data = array();
        if (count($allTranslations)) {
            foreach ($allTranslations AS $module => $keys) {
                foreach ($keys AS $key => $langs) {

                    $firstNotEmptyValue = '';
                    foreach ($langs AS $value) {
                        if (empty($firstNotEmptyValue) && !empty($value)) {
                            $firstNotEmptyValue = $value;
                        }
                    }

                    if (!empty($firstNotEmptyValue)) {
                        foreach ($langs AS $langId => $value) {
							Db_Locale_Untranslated::deleteUntranslated($langId, $module, $key);
                            $data[] = array(
                                't_lang_id' => $langId,
                                't_module' => strtolower($module),
                                't_key' => strtolower($key),
                                't_content' => (!empty($value) ? $value : $firstNotEmptyValue),
                            );
                        }
                    }
                }
            }
			Db_Locale_Translations::insertBatch($data, true);
        }

        return array(
			'type' => 'redirect',
			'content' => $redirect
		);
    }

    public function deleteAllUntranslatedAction(){
		perm('TRANSLATIONS_EDIT', '/locale/translations');
		Db_Locale_Untranslated::deleteAllUntranslated();
        $redirect = get('redirect', 'string');
        return array(
            'type' => 'redirect',
            'content' => $redirect
        );
    }

    public function saveCellAjaxAction() {
		perm('TRANSLATIONS_EDIT', '/locale/translations');
        $translateValue = explode('_AND_', post('value', 'string'));
        $translateValue[2] = ($translateValue[2] == 0 ? true : false );
        $this->message = t(T_FORM_MSG, 'success');
        if(!Db_Locale_Translations::setHtmlTranslation($translateValue[0], $translateValue[1], $translateValue[2])) {
            $this->error = true;
            $this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
        }
        return array(
            'type' => 'encoded_json',
            'content' => $this->jsonResult($this->error, $this->message, !$this->error)
        );
    }

	public function machineTranslateAction() {
		$toTranslate = post('toTranslate', 'array');
		if ($toTranslate) {
			$result = array();
			$encodedString = urlencode($toTranslate['string']);
			$originalLang = $toTranslate['originalLang'];
			foreach ($toTranslate['langs'] as $lang) {
				$response = json_decode(file_get_contents("http://mymemory.translated.net/api/get?q={$encodedString}&langpair={$originalLang}|{$lang}"), true);
				$result[$lang] = $response['responseData']['translatedText'];
			}
			return array(
				'type' => 'encoded_json',
				'content' => json_encode($result)
			);
		}
	}

	public function ajaxSaveKeyAction() {
		$key = post('key', 'str');
		$module = post('module', 'str');
		$currentKey = post('currentKey', 'str');
		$ids = Db_Locale_Translations::getTranslationIdByModuleAndKey($module, $key);
		$dataResult = array();

		foreach($ids as $id) {
			$dataResult[] = array(
				'id' => $id,
				't_module' => $module,
				't_key' => $currentKey
			);
		}
		$result = Db_Locale_Translations::insertBatch($dataResult, true);

		if(!$result) {
			$currentKey = $key;
		}
		return array(
			'type' => 'json',
			'content' => $currentKey
		);
	}
}
